package com.itheima.controller;

import com.github.pagehelper.PageInfo;
import com.itheima.domain.Student;
import com.itheima.domain.Student;
import com.itheima.service.StudentService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@RestController
@RequestMapping("/student")
public class StudentController {

    @Reference
    private StudentService studentService;

    @RequestMapping("/findAll")
    public ModelAndView findAll(@RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "5") Integer pageSize) {
        ModelAndView mv = new ModelAndView();

        PageInfo<Student> info = studentService.pageQuery(pageNum, pageSize);
        List<Student> list = info.getList();


        if (list.isEmpty()) {
            mv.addObject("message_findAll", "暂无数据");
            mv.setViewName("student");
            return mv;
        }


        mv.addObject("page", info);
        mv.setViewName("allStu");
        return mv;
    }

    @RequestMapping("/findById")
    public ModelAndView findById(Integer id) {
        Student student = studentService.findById(id);
        ModelAndView mv = new ModelAndView();
        if (student == null) {
            mv.addObject("message_findById", "您查询的id不存在");
            mv.setViewName("student");
            return mv;
        }

        mv.addObject("stu", student);
        mv.setViewName("itemDetail");
        return mv;
    }

    @RequestMapping("/add")
    public ModelAndView add(@Validated Student student, Errors errors) {
        ModelAndView mv = new ModelAndView();

        List<FieldError> fieldErrors = errors.getFieldErrors();
        for (FieldError error : fieldErrors) {
            if (error == null ) {
                mv.setViewName("student");
                Integer count = studentService.save(student);
            } else {
                mv.addObject("message_addUser",error.getDefaultMessage());
                mv.setViewName("student");

            }
        }

        return mv;

    }
}
